import { defineComponent, onMounted, type PropType, ref, toRefs } from 'vue'
import { Button, Card, Col, Form, FormItem, Input, Row, Select, Textarea } from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useForm } from './use-form'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import { useRouter } from 'vue-router'
import type { Router } from 'vue-router'
import { sm4DECrypt } from '@/utils/crypt/sm4Utils'

const UserDetail = defineComponent({
  name: 'UserDetail',
  props: {
    userCode: {
      type: [String, Number],
      required: false
    },
    businessType: {
      type: String as PropType<BusinessPageTypeEnum>,
      required: true,
      validator: (value: string) => {
        // 检查传入的值是否在枚举的有效值中
        return Object.values(BusinessPageTypeEnum).includes(value as BusinessPageTypeEnum)
      }
    }
  },
  emits: ['cancelModal', 'confirmModal'],
  setup(props, ctx) {
    const router: Router = useRouter()
    const roleOptionList = ref<any[]>([])
    const password = ref<string>('********')
    const { meta, state, initForm, getFormValues } = useForm()
    const { status, createOrUpdate, getUserById, getRoleList, getUserPasswordByCode } = useDetail(getFormValues)

    const handleCommit = async () => {
      await createOrUpdate()
      initForm()
      password.value = '********'
      ctx.emit('confirmModal')
    }

    const resetForm = () => {
      initForm()
      password.value = '********'
      ctx.emit('cancelModal')
    }

    const fetchRoleList = async () => {
      roleOptionList.value = await getRoleList()
    }

    const showPassword = async () => {
      // 查询密码
      const data = await getUserPasswordByCode(state.detailForm.userCode)
      password.value = sm4DECrypt(data.password)
    }

    const toAddRole = () => {
      router.push({ path: 'role' })
    }
    const fetchData = async () => {
      if (props.businessType === BusinessPageTypeEnum.UPDATE || props.businessType === BusinessPageTypeEnum.DETAIL) {
        // 查询值
        state.detailForm = await getUserById(props.userCode)
      }
      // 获取下拉框值
      await fetchRoleList()
    }

    onMounted(async () => {
      await fetchData()
    })

    return {
      ...toRefs(props),
      ...toRefs(state),
      ...toRefs(status),
      ...toRefs(meta),
      roleOptionList,
      password,
      handleCommit,
      resetForm,
      toAddRole,
      showPassword
    }
  },

  render() {
    const {
      businessType,
      detailForm,
      rules,
      roleOptionList,
      password,
      handleCommit,
      resetForm,
      toAddRole,
      showPassword
    } = this
    return (
      <>
        <Card>
          <Form
            ref='detailFormRef'
            model={detailForm}
            rules={rules}
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 18 }}
            style={{ width: '80%' }}
            onFinish={handleCommit}
          >
            <FormItem label='员工姓名' name='username'>
              <Input
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.username, 'value']}
                showCount
                maxlength={30}
                placeholder='请输入员工姓名'
              />
            </FormItem>

            <FormItem label='手机号' name='telephone'>
              <Input
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.telephone, 'value']}
                maxlength={11}
                placeholder='请输入手机号'
              />
            </FormItem>
            {businessType === BusinessPageTypeEnum.DETAIL && (
              <FormItem label='密码' name='username'>
                <Row gutter={12}>
                  <Col span={18}>
                    <Input disabled v-model={[password, 'value']} maxlength={30} placeholder='密码' />
                  </Col>
                  <Col span={6}>
                    <Button type={'link'} onClick={showPassword} v-auth={['sys:user:view-password']}>
                      查看
                    </Button>
                  </Col>
                </Row>
              </FormItem>
            )}
            <FormItem label='角色' name='description'>
              <Row gutter={12}>
                <Col span={18}>
                  <Select
                    disabled={businessType === BusinessPageTypeEnum.DETAIL}
                    mode='multiple'
                    v-model={[detailForm.roleIds, 'value']}
                    options={roleOptionList}
                  />
                </Col>
                {businessType !== BusinessPageTypeEnum.DETAIL && (
                  <Col span={6}>
                    <Button type={'link'} onClick={toAddRole}>
                      新建角色
                    </Button>
                  </Col>
                )}
              </Row>
            </FormItem>
            <FormItem label='描述' name='description'>
              <Textarea
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.description, 'value']}
                maxlength={200}
                rows={3}
                placeholder='请输入'
              />
            </FormItem>

            <FormItem wrapperCol={{ span: 12, offset: 12 }}>
              {businessType === BusinessPageTypeEnum.DETAIL && <Button onClick={resetForm}>返回</Button>}
              {businessType !== BusinessPageTypeEnum.DETAIL && (
                <>
                  <Button type='primary' htmlType='submit'>
                    提交
                  </Button>
                  <Button style={{ marginLeft: '12px' }} onClick={resetForm}>
                    取消
                  </Button>
                </>
              )}
            </FormItem>
          </Form>
        </Card>
      </>
    )
  }
})
export default UserDetail
